package com.heima.admin.service.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.IdsUtils;
import org.aspectj.weaver.patterns.IToken;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUser adUser) {
        //参数检查
        if (adUser.getName()==null||adUser.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"请输入用户名和密码");
        }
        //查数据库
        LambdaQueryWrapper<AdUser> queryMapper=new LambdaQueryWrapper<>();
        queryMapper.eq(AdUser::getName,adUser.getName());
        AdUser userInDb = getOne(queryMapper);
        // 获取加密后的字符串
        String pswd = DigestUtils.md5DigestAsHex((adUser.getPassword() + userInDb.getSalt()).getBytes());
        if (userInDb!=null&&pswd.equals(userInDb.getPassword())){
            // 数据库对象不为空同时前端密码和salt加密后和数据库一致
            // 创建jwt并返回
            Map<String,Object> map = new HashMap<>();
                // 将核心信息置空
                userInDb.setPassword("");
                userInDb.setSalt("");
            map.put("data",userInDb);
            //创建jwt
            String token = AppJwtUtil.getToken(userInDb.getId().longValue());
            map.put("token", token);
            //返回数据
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码错误");
        }
    }
}
